package HW2_1.Firefox;

import static org.junit.Assert.fail;

import java.util.concurrent.TimeUnit;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.firefox.internal.ProfilesIni;
import org.openqa.selenium.support.ui.Select;




public class b_new_user {
	private WebDriver driver;
	private String baseUrl;
	private StringBuffer verificationErrors = new StringBuffer();
	@Before
	public void setUp() throws Exception {
		
		 ProfilesIni allProfiles = new ProfilesIni(); 
	     FirefoxProfile profile = allProfiles.getProfile("default"); 
	     driver = new FirefoxDriver(profile); 
		 baseUrl = "http://localhost/tools/";
		 driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
	}

	@Test
	public void a_new_user() throws Exception {
		GoToMainPage();
		LoginAs("admin", "admin");
		AddNewUser("kalinka", "kalinka955@mail.ru", "kalinka");
		logout();
	}

	private void logout() {
		driver.findElement(By.linkText("Log out")).click();
		driver.switchTo().alert().accept();
	}

	

	private void AddNewUser(String userName, String email, String password) {
		driver.findElement(By.linkText("User management")).click();
		driver.findElement(By.id("username")).clear();
		driver.findElement(By.id("username")).sendKeys(userName);
		driver.findElement(By.name("email")).clear();
		driver.findElement(By.name("email")).sendKeys(email);
		driver.findElement(By.id("password")).clear();
		driver.findElement(By.id("password")).sendKeys(password);
		driver.findElement(By.id("password2")).clear();
		driver.findElement(By.id("password2")).sendKeys(password);
		new Select(driver.findElement(By.name("permission"))).selectByVisibleText("Admin");
		driver.findElement(By.name("submit")).click();
	}
	
	
	private void LoginAs(String username, String password) {
		driver.findElement(By.id("username")).clear();
		driver.findElement(By.id("username")).sendKeys(username);
		driver.findElement(By.name("password")).clear();
		driver.findElement(By.name("password")).sendKeys(password);
		driver.findElement(By.name("submit")).click();
	
	}

	private void GoToMainPage() {
		driver.get(baseUrl + "/php4dvd/");
	}

		@After
	public void tearDown() throws Exception {
		driver.quit();
		String verificationErrorString = verificationErrors.toString();
		if (!"".equals(verificationErrorString)) {
			fail(verificationErrorString);
		}
	}

	private boolean isElementPresent(By by) {
		try {
			driver.findElement(by);
			return true;
		} catch (NoSuchElementException e) {
			return false;
		}
	}
}
